<template>
  <el-container>
    <!-- <RegionTree style="margin-top: 16px" @on-choose-region="filetrRegion" /> -->
    <el-main>
      <div class="default-main ba-table-box">
        <TableHeader
          :buttons="[
            'refresh',
            'add',
            'edit',
            'remove',
            'comSearch',
            'columnDisplay',
          ]"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
        <!-- 表单 -->
        <PopupForm v-if="baTable.form.operate" ref="formRef" />
      </div>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import { ref, provide, onMounted, markRaw, onBeforeUnmount } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { BusinessMInfo } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { useRouter, useRoute } from "vue-router";
import type { ElForm } from "element-plus";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { useBusiness } from "@/store/backend/BusinessM/info";
import PopupForm from "./popupForm.vue";
import { cloneDeep } from "lodash";
import { useRegion } from "@/store/backend/SysM/region";
import CascaderBusiness from "@/components/CascaderForBusiness/index.vue";
import { useNavTabs } from "@/store/navTabs";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const router = useRouter();
const business = useBusiness();
const region = useRegion();
const route = useRoute();
const formRef = ref();
const navTabs = useNavTabs();

const { proxy } = useCurrentInstance();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + BusinessMInfo)
      ? (navTabs as any).pageSizeMap.get(route.path + BusinessMInfo)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(BusinessMInfo),
  {
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      // { label: "企业ID", prop: "id", align: "center", operator: false },
      {
        show: filedShowOff("name"),
        label: "企业名称",
        prop: "name",
        align: "center",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("type"),
        label: "所属行业",
        prop: "type",
        align: "center",
        operatorPlaceholder: "精确搜索",
      },
      {
        show: filedShowOff("addr"),
        label: "地址",
        prop: "addr",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("creditCode"),
        label: "企业社会信用代码",
        prop: "creditCode",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("regionName"),
        label: "所属区域",
        prop: "regionName",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("user"),
        label: "联系人",
        prop: "user",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("tel"),
        label: "联系方式",
        prop: "tel",
        align: "center",
        operator: false,
      },
      // { label: "指定银行", prop: "bank", align: "center" },
      // { label: "银行客户经理", prop: "bank_manager", align: "center" },
      // {
      //   label: "创建时间",
      //   prop: "createTime",
      //   align: "center",
      //   render: "datetime",
      //   operator: false,
      // },
      {
        show: filedShowOff("state"),
        label: "企业状态",
        prop: "state",
        render: "tag",
        align: "center",
        custom: { 0: "success", 1: "danger" },
        replaceValue: {
          0: "正常",
          1: "异常",
        },
        operator: false,
      },
      {
        show: false,
        label: "选择区域",
        prop: "",
        align: "center",
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(CascaderBusiness),
      },
      {
        show: operatorShowOff([route.path + "/remove", route.path + "/edit"]),
        label: "操作",
        align: "center",
        width: "160",
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "info",
            title: "详情",
            text: "",
            type: "primary",
            icon: "iconfont icon-chaxunyujisuan",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return false;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "query",
            name: "query",
            title: "台账",
            text: "",
            type: "primary",
            icon: "iconfont icon-icon-project",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return false;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "tipButton",
            name: "edit",
            title: "编辑",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return false;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "confirmButton",
            name: "remove",
            title: "删除",
            text: "",
            type: "danger",
            icon: "el-icon-DeleteFilled",
            class: "table-row-delete",
            popconfirm: {
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              confirmButtonType: "danger",
              title: "确认删除？",
            },
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return false;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
        operator: false,
      },
    ],
    filter: {
      // id: Local.get("adminInfo")?.companyid,
      regions: [] + "",
      pageSize: pageSizeKeep(),
      // name: route.query.name,
    },
    acceptQuery: false,
  },
  {
    defaultItems: {
      state: 0,
    },
  },
  {
    // 提交前
    onSubmit: (params: { formEl: InstanceType<typeof ElForm> }) => {
      var items = cloneDeep(baTable.form.items!);

      //!企业匹配的区域节点包含父子联动 同时格式要求为字符串 待后端决定传递数据类型
      items.region = formRef.value.getCheckeds().join(",");
      items.regionbo =
        formRef.value.getCheckedOne()[formRef.value.getCheckedOne().length - 1];
      console.log("items", items);
      for (const key in items) {
        if (items[key] === null) {
          delete items[key];
        }
      }

      // 表单验证通过后执行的api请求操作
      let submitCallback = () => {
        baTable.form.submitLoading = true;
        baTable.api
          .postData(baTable.form.operate!, items)
          .then((res) => {
            baTable.onTableHeaderAction("refresh", {});
            baTable.form.submitLoading = false;
            baTable.form.operateIds?.shift();
            if (baTable.form.operateIds!.length > 0) {
              baTable.toggleForm("edit", baTable.form.operateIds);
            } else {
              baTable.toggleForm();
            }
            baTable.runAfter("onSubmit", { res });
          })
          .catch((err) => {
            baTable.form.submitLoading = false;
          });
      };

      if (params.formEl) {
        baTable.form.ref = params.formEl;
        params.formEl.validate((valid) => {
          if (valid) {
            submitCallback();
          }
        });
      } else {
        submitCallback();
      }
      return false;
    },
  }
);

interface Region {
  address: string | null;
  addressDetail: string | null;
  areaFlag: string | null;
  areaId: number;
  areaName: string | null;
  areaNo: string | null;
  children: Region[];
  createBy: string | null;
  createTime: string | null;
  endTime: string | null;
  params: any;
  parentId: number;
  searchValue: string | null;
  startTime: string | null;
  updateBy: string | null;
  updateTime: string | null;
}
//接收区域树传递过来的数据
// const filetrRegion = (row: Region, node: any) => {
//   baTable.table.loading = true;
//   //企业用户选择区域只会刷新
//   // if (Local.get("adminInfo")?.userType === "2") {
//   //   return baTable.onTableHeaderAction("refresh", {});
//   // }
//   //判断node属性中checkedNodes是否为空
//   if (node.checkedKeys.length == 0) {
//     //表示取消选择直接调用刷新表单方法
//     baTable.comSearch.form = Object.assign(baTable.comSearch.form, {
//       regions: [] + "",
//     });
//     baTable.onTableHeaderAction("refresh", {});
//   } else {
//     baTable.comSearch.form = Object.assign(baTable.comSearch.form, {
//       regions: node.checkedKeys + "",
//     });
//     business
//       .roleCompany(baTable.comSearch.form)
//       .then((res: any) => {
//         console.log("resroleCompany", res);
//         baTable.table.loading = false;
//         baTable.table.total = res.total;
//         baTable.table.data = res.rows;
//       })
//       .catch(() => {
//         baTable.table.loading = false;
//       });
//     // baTable.getList(BusinessMInfo);
//   }
// };

const infoButtonClick = (name: string, row: any) => {
  business.$patch((state) => {
    state.loading = true;
    state.query = name;
    state.item = row;
  });
  //!待跳转到实时设备详情 通常是获取拿到id获取数据后跳转
  router.push({
    path: "/admin/BusinessM/detail",
    query: { institution: name },
  });
};
//跳转到企业台账页面
const ledgerButtonClick = (name: string, row: any) => {
  business.$patch((state) => {
    state.loading = true;
    state.query = name;
    state.item = row;
  });
  router.push({
    path: "/admin/BusinessM/ledgerDetail",
    query: {
      companyId: row.id,
    },
  });
};

onMounted(() => {
  //全局事件总线
  const { proxy } = useCurrentInstance();
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(BusinessMInfo);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow | any }) => {
      if (!baTable.activate) return;
      //回滚功能暂无
      if (data.name == "rollback") {
        // onRollback([data.row[baTable.table.pk!]])
      } else if (data.name == "info") {
        // 主键字段 pk: "name",
        infoButtonClick(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as any
        );
      } else if (data.name == "query") {
        // 主键字段 pk: "name",
        ledgerButtonClick(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as any
        );
      }
    }
  );
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
// watch(
//   () => region.userRegionByRole,
//   (newValue, oldValue) => {
//     console.log("newValue", newValue);
//     if (newValue.length !== 0) {
//       baTable.getList(BusinessMInfo);
//     }
//   },
//   {
//     immediate: true, // 值如果是true会打开首次监听
//   }
// );
onBeforeUnmount(() => {
  proxy.eventBus.off("onTableButtonClick");
  proxy.eventBus.off("changeFileId");
});
</script>
<style lang="scss" scoped>
.el-main {
  padding: 0;
}
</style>
